import React, { useRef, useState, useEffect } from 'react';
import { Tooltip } from 'element-react';

const AutoTooltip = ({ className, style, ...rest }) => {
    const tagLabelRef = useRef(null);
    const [containerWidth, setContainerWidth] = useState(0);
    const [contentWidth, setContentWidth] = useState(0);

    const handleResize = () => {
        if (tagLabelRef.current) {
            setContainerWidth(tagLabelRef.current.scrollWidth);
            setContentWidth(tagLabelRef.current.clientWidth);
        }
    };

    useEffect(() => {
        if (tagLabelRef.current) {
            setContainerWidth(tagLabelRef.current.scrollWidth);
            setContentWidth(tagLabelRef.current.clientWidth);
        }
        window.addEventListener('resize', handleResize);
        return () => {
            window.removeEventListener('resize', handleResize);
        };
    }, []);

    const isDisabled = !(containerWidth > contentWidth);

    return (
        <Tooltip
            {...rest}
            disabled={isDisabled}
            effect="dark"
            placement="bottom"
            popperClass="auto-tooltip-popper"
        >
            <div
                ref={tagLabelRef}
                className={`auto-tooltip ${className || ''}`}
                style={style}
            >
                {props.children}
            </div>
        </Tooltip>
    );
};

export default AutoTooltip;